<?php


namespace App\Common;

use App\Exceptions\BusinessException;
use Carbon\Carbon;
use Godruoyi\Snowflake\Snowflake;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;

/**
 * 工具类
 *
 * @package App\Http\Common
 */
class Tools
{
    /**
     * 获取uniqueId
     *
     * @param string $prefix
     * @return string
     */
    public static function getUniqid($prefix = '')
    {
        return uniqid($prefix,true);
    }

    /**
     * 生成编号
     *
     * @param string $bnKey
     * @return string
     * @throws BusinessException
     */
    public static function buildBn(string $bnKey)
    {
        if(!key_exists($bnKey, BnFormatConfig::BN_FORMAT_MAP)) {
            throw new BusinessException(ResponseCode::BN_KEY_NOT_FOUND);
        }
        // 获取缓存自增值
        $count = 1;
        if(Cache::has($bnKey)) {
            $count = Cache::get($bnKey);
        } else {
            Cache::put($bnKey, 1, Carbon::now()->diffInSeconds(Carbon::tomorrow()));
        }
        $prefix = BnFormatConfig::BN_FORMAT_MAP[$bnKey]['prefix'];
        $pad = BnFormatConfig::BN_FORMAT_MAP[$bnKey]['pad'];
        $bn = $prefix . date('Ymd') . str_pad($count,$pad,'0',STR_PAD_LEFT);
        Cache::increment($bnKey);
        return $bn;
    }

    /**
     * 获取当前的毫秒数
     *
     * @return float
     */
    public static function getMsec()
    {
        list($msec, $sec) = explode(' ', microtime());
        return (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);
    }

    /**
     * 获取资源路径（去除域名）
     *
     * @param string $url
     * @return mixed
     */
    public static function getUri(string $url)
    {
        return str_replace(config('app.base_url'), '', $url);
    }

    public static function encryptMobile(string $mobile)
    {
        return substr($mobile, 0, 3).'****'.substr($mobile, 7);
    }

    /**
     * 转化地区信息
     *
     * @param array $region
     * @return array
     */
    public static function parseRegion(array $region)
    {
        $regions = collect($region);
        return [
            'region_id' => $regions->implode('value', '/'),
            'region' => $regions->implode('label', '/')
        ];
    }

    /**
     * 生成雪花id
     *
     * @param int $dataCenterId
     * @param int $workerId
     * @return string
     */
    public static function nextId(int $dataCenterId = 1, int $workerId = 1)
    {
        $snowflake = new Snowflake($dataCenterId, $workerId);
        return $snowflake->id();
    }

    /**
     * 获取当前时间（指定格式）
     *
     * @param string $format
     * @return string
     */
    public static function getDateTime(string $format = 'Y-m-d H:i:s')
    {
        return Carbon::now()->format($format);
    }
}
